package com.bitrate.dagger.gateway.cros;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.MDC;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 网关层跨域过滤器
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableConfigurationProperties(CorsProperties.class)
@WebFilter(filterName = "CorsFilter", urlPatterns = "/*")
public class CorsFilter implements Filter {

	private final CorsProperties properties;

	public CorsFilter(CorsProperties properties) {
		this.properties = properties;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		MDC.put("R-TraceId", "XLog-" + RandomUtil.randomString(16));
		HttpServletRequest httpServletRequest = (HttpServletRequest) req;
		HttpServletResponse httpServletResponse = (HttpServletResponse) res;
		httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
		httpServletResponse.setHeader("Access-Control-Request-Method", properties.getRequestMethod());
		httpServletResponse.setHeader("Access-Control-Allow-Methods", properties.getAllowMethods());
		httpServletResponse.setHeader("Access-Control-Max-Age", properties.getMaxAge().toString());
		httpServletResponse.setHeader("Access-Control-Allow-Headers", properties.getAllowHeaders());
		httpServletResponse.setHeader("Access-Control-Allow-Credentials",
				properties.getAllowCredentials() ? "true" : "false");
		chain.doFilter(httpServletRequest, httpServletResponse);
	}

	@Override
	public void init(FilterConfig filterConfig) {
		log.info("------------- CorsFilter Init Success-------------------");
	}

	public void destroy() {

	}

}